package com.way.filemanager.fragment.FileList;

import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;

import com.way.filemanager.ui.IconHolder;
import com.way.filemanager.util.MimeTypeHelper;

import java.util.ArrayList;
import java.util.List;

public class IconDrawableManager{
    private static final String TAG = "IconDrawableManager";
    Context mContext;
    List<String> mList ;
    GetIconCb mGetIconCb;
    int  mStartVisiblePositon;
    int  mEndVisiblePositon;
    boolean IsForceStop = false;
    final int MAX_CACHE_ICON_NUM = 30;
    IconHolder mIconHolder;
    //private List<Drawable> mIcons;
    //private List<String> mFullPath;
    //private int[] mMapIndex;
    CacheFifo [] mCacheObject;
    public IconDrawableManager(Context m,List<String> list,GetIconCb cb)
    {
        mContext = m;
        mList = new ArrayList<String>();
        mList.clear();
        if(list != null)
            mList.addAll(list);

        mGetIconCb = cb;
        mIconHolder = new IconHolder(mContext ,false);

        //mIcons = new ArrayList<Drawable>();
        //mFullPath = new ArrayList<String>();
        //mMapIndex = new int[MAX_CACHE_ICON_NUM];
        mCacheObject = new CacheFifo[MAX_CACHE_ICON_NUM];
    }
    public int SetFocusPosition(int startPos,int EndPos)
    {
        mStartVisiblePositon = startPos;
        mEndVisiblePositon = EndPos;
        RestartScan();
        return 0;
    }

    public void ChangeWorkingList(List<String> list,int startPos,int EndPos)
    {
        if(mThread !=null)
        {
            ForceStopScan();
            try {
                mThread.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mThread = null;
        }

        mList.clear();
        if(list != null)
            mList.addAll(list);
        for(int index =0;index < MAX_CACHE_ICON_NUM;index++)
        {
            if(mCacheObject[index] != null)
            {
                mCacheObject[index] = null;
            }
        }
        mStartVisiblePositon = startPos;
        mEndVisiblePositon = EndPos;
        RestartScan();
    }
    public void ForceStopScan()
    {
        IsForceStop = true;
    }
    public void RestartScan()
    {
        if(mThread !=null)
        {
            ForceStopScan();
            try {
                mThread.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mThread = null;
        }
        IsForceStop = false;
        mThread = new Thread(mRun);
        mThread.start();
    }
    Thread mThread ;
    Runnable mRun= new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Log.v(TAG,"Runnable mRun ====================== >>>>>>>");
            int MapToRealIndex = 0;
            boolean bIsFind = false;

            {
                for(int count = 0;(count < MAX_CACHE_ICON_NUM)&& (!IsForceStop)&&(count < mList.size()) ;count ++)
                {
                    //if(mCacheObject[count] != null)
                    {
                        Log.v(TAG,"count:"+count);
                        MapToRealIndex = cachePriority[count] + mStartVisiblePositon;
                        Log.v(TAG,"MapToRealIndex:"+MapToRealIndex);
                        if(MapToRealIndex<0)
                            continue;
                        if(MapToRealIndex >= mList.size())
                            continue;
                        String path = mList.get(MapToRealIndex);
                        bIsFind = false;
//                        Log.v(TAG,"path:"+path);
                        for(int search = 0;search < MAX_CACHE_ICON_NUM ;search ++)
                        {
                            if(mCacheObject[search] != null)
                            {
                                if(path.equals(mCacheObject[search].mFilename))
                                {
                                    bIsFind = true;
                                    break;
                                }
                            }
                        }
                        if(!bIsFind)
                        {
                            CacheFifo mCacheFifo = new CacheFifo();
                            mCacheFifo.mFilename = path;
                            mCacheFifo.mMapIndex = MapToRealIndex;
                            if(mGetIconCb!=null)
                                mCacheFifo.mIcons = mGetIconCb.GeticonByObject(path);
                            Log.v(TAG,"mCacheFifo.mIcons:"+mCacheFifo.mIcons);
                            for(int findNull = 0;findNull < MAX_CACHE_ICON_NUM ;findNull ++)
                            {
                                //Log.v(TAG,"mCacheObject[findNull]:"+mCacheObject[findNull]);
                                if(mCacheObject[findNull] == null)
                                {
                                    mCacheObject[findNull] = mCacheFifo;
                                    Log.v(TAG,"mCacheObject[findNull]:"+findNull);
                                    break;
                                }
                                else
                                {
                                    //Log.v(TAG,"mCacheObject[findNull].mMapIndex:"+mCacheObject[findNull].mMapIndex);
                                    if((mCacheObject[findNull].mMapIndex >= mStartVisiblePositon+20)
                                            ||(mCacheObject[findNull].mMapIndex < mStartVisiblePositon- 9))
                                    {
                                        mCacheObject[findNull] = mCacheFifo;
                                        Log.v(TAG,"mCacheObject[findNull]:"+findNull);
                                        break;
                                    }
                                }
                            }
                            if((MapToRealIndex >= mStartVisiblePositon)&&(MapToRealIndex <= mEndVisiblePositon))
                            {
                                if(mGetIconCb != null)
                                    mGetIconCb.IconCacheChangeNotify(count);
                            }
                        }

                    }
                }
            }
        }
    };

    public Drawable getIcon(String Filename)
    {
        Drawable ret = null ;
        for(int index = 0;index < MAX_CACHE_ICON_NUM;index++)
        {
            //Log.v(TAG, "mCacheObject[index]:" +mCacheObject[index]);
            if(mCacheObject[index] != null)
            {
                if(mCacheObject[index].mFilename.equals(Filename))
                    ret = mCacheObject[index].mIcons;
            }
        }
        if(ret == null)
        {
            String iconId = MimeTypeHelper.getFileIcon(mContext, Filename);
            ret = mIconHolder.getDrawable(iconId);
        }
        return ret;
    }
    Drawable getDefaultIcon(String Filename)
    {
        String iconId = MimeTypeHelper.getFileIcon(mContext, Filename);
        return mIconHolder.getDrawable(iconId);

    }
    public interface GetIconCb
    {
        Drawable GeticonByObject(String input);
        int IconCacheChangeNotify(int status);
    }

    class CacheFifo{
        public Drawable mIcons;
        public String mFilename;
        public int mMapIndex;
    }
    int cachePriority[]={0,1,2,3,4,5,6,7,8,9,-1,10,-2,11,-3,12,-4,13,-5,14,-6,15,-7,16,-8,17,-9,18,-10,19};

    public static String GetThumbnailPath(Context context, String file_path) {
        // view plaincopy to clipboardprint?
        String[] projection2 = {
            "_id",
        // "_data"
        };
        Uri uri2 = MediaStore.Images.Media.getContentUri("external");
        String escape_path = file_path.replace("'", "''");
        String where = String.format("_data = '%s' ", escape_path);
        Cursor c2 = Media.query(context.getContentResolver(), uri2, projection2, where, null);
        if(c2 == null)
            return null;
        if(c2.getCount() < 1)
        {
            c2.close();
            return null;
        }
        int index = c2.getColumnIndexOrThrow("_id");
        Log.v(TAG, "_id index:" + index);
        c2.moveToFirst();
        long image_id = c2.getLong(index);
        Log.v(TAG, "image_id:" + image_id);
        //view plaincopy to clipboardprint?
        String[] projection = {
            "_data",
        // "image_id"
        };
        c2.close();
        Cursor c = Thumbnails.queryMiniThumbnail(context.getContentResolver(), image_id,
                Thumbnails.MINI_KIND, projection);
        if(c ==null)
            return null;
        if(c.getCount() < 1)
        {
            c.close();
            return null;
        }
        c.moveToFirst();
        Log.v(TAG, "_data c.getCount():" + c.getCount());
        index = c.getColumnIndexOrThrow("_data");
        Log.v(TAG, "_data index:" + index);

        if(index <0)
        {
            c.close();
            return null;
        }
        String thumbnail_path = c.getString(index);
        c.close();
        return thumbnail_path;
    }
}
